package org.springframework.samples.petclinic

import java.lang.Integer
import java.util.HashSet
import scala.collection.jcl.Buffer 
import scala.collection.immutable.Set
import scala.reflect.BeanProperty

import org.springframework.beans.support.MutableSortDefinition
import org.springframework.beans.support.PropertyComparator
import org.springframework.core.style.ToStringCreator


class Owner(id:Integer, firstName:String, lastName:String, 
            @BeanProperty var address:String, @BeanProperty var city:String, @BeanProperty var telephone:String,
            var pets: java.util.Set[Pet]) extends Person(id, firstName, lastName) {

  def this() = this(null, null, null, null, null, null, null)
  
  protected def setPetsInternal(pets:java.util.Set[Pet]) = {
    this.pets = pets
  }

  protected def getPetsInternal:java.util.Set[Pet] = {
    if (pets == null) {
      pets = new HashSet[Pet]
    }
    pets
  }
  
  def getPets:java.util.List[Pet] = {
    var sortedPets:java.util.List[Pet] = new java.util.ArrayList[Pet](getPetsInternal)
    PropertyComparator.sort(sortedPets, new MutableSortDefinition("name", true, true))
    java.util.Collections.unmodifiableList[Pet](sortedPets)
  }
  
  def addPet(pet:Pet) {
    getPetsInternal.add(pet)
    pet.owner = this
  }
  
  def getPet(name:String):Pet = {
    getPet(name, false)
  }
  

  def getPet(name:String, ignoreNew:Boolean):Pet = {
    val nameLow = name.toLowerCase()

    for (pet <- new ForeachIterator(getPetsInternal.iterator)) {
      if (!ignoreNew || !pet.isNew) {
        var compName:String = pet.name
        compName = compName.toLowerCase()
        if (compName.equals(nameLow)) {
          return pet
        }
      }
    } 
    return null
  }
  
  override def toString:String = {
    new ToStringCreator(this)
    .append("id", this.id)
    .append("new", this.isNew)
    .append("lastName", this.lastName)
    .append("firstName", this.firstName)
    .append("address", this.address)
    .append("city", this.city)
    .append("telephone", this.telephone)
    .toString()
  }
  

}
